//
//  MHDataHelper.m
//  NewChat
//
//  Created by 马欢 on 16/3/4.
//  Copyright © 2016年 蓝鸥. All rights reserved.
//

#import "MHDataHelper.h"
#import "FindModel.h"
#import "ReplyModel.h"
#import "MHShareDataBlock.h"
#import "SongModel.h"
#import "PlayerManager.h"


#define Manager [PlayerManager defaultManager]

@interface MHDataHelper ()

@property (nonatomic,strong)NSMutableArray *hotArray;
@property (nonatomic,strong)NSMutableArray *recentlyArray;

@property (nonatomic,strong)NSMutableArray *hotChatArray;
@property (nonatomic,strong)NSMutableArray *replyArray;
@property (nonatomic,strong)NSMutableArray *myCollectArray;

@property (nonatomic,strong)NSMutableArray *allHerTopics;//他的话题
@property (nonatomic,strong)NSMutableArray *allHerReplys;//他的回复
@property (nonatomic,strong)NSMutableArray *allMyAttentionTopics;//他关注的好友的话题

@property (nonatomic,strong)NSMutableArray *onlineUsers;//在线用户
//@property (nonatomic,strong)NSMutableArray *allSongsArray;//歌曲
@property (nonatomic,strong)NSMutableArray *topicNumbers;
@end


@implementation MHDataHelper
//单例
+(instancetype)shareDataHelper{
    static MHDataHelper *helper = nil;
    //  原来那种创建单例的方式没有考虑到线程
    //  保证里边的内容只会执行一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        helper = [[MHDataHelper alloc]init];
        helper.pushIndex = 0;
        RealReachability *reachability = [RealReachability sharedInstance];
        ReachabilityStatus status = [reachability currentReachabilityStatus];
        if (status == RealStatusNotReachable) {
            
        }else{
        [helper getData];//一开始就获取音乐播放数据
        }
    });
    return helper;
}
//查询所有在线用户
-(void)requestAllOnlineUsersDidFinished:(SUCCESS)success{
    AVQuery *query = [AVUser query];
    [query includeKey:@"status"];
    [query whereKey:@"status" equalTo:@"在线"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
       
        self.onlineUsers = [NSMutableArray arrayWithArray:objects];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            success(_onlineUsers);
        });
        
    }];
    
}

-(void)getData//异步获取数据，保证早获取数据，不影响运行
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
        [MHShareDataBlock GETAsynchronousBlockWithURL:AllLike PassBlock:^(NSData *data) {
            
            if (_allSongsArray.count != 0) {
                [self.allSongsArray removeAllObjects];
            }
            NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
            for (NSDictionary *dic in [Dic[@"data"] valueForKey:@"songs"]) {
                SongModel *song = [SongModel new];
                [song setValuesForKeysWithDictionary:dic];
                if (song.urlList.count > 0) {
                    [self.allSongsArray addObject:song];
                }
            }
        }];
    });
}


//=====================数据请求=======================
//发现－-最新 ok
-(void)requestRecentlyArraydidFinish:(SUCCESS)success{
    if (_recentlyArray.count != 0) {
        [_recentlyArray removeAllObjects];
    }
    AVQuery *query = [FindModel query];
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    //设置缓存有效期
    query.maxCacheAge = 24*3600;
    [query includeKey:@"owner"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.recentlyArray = [NSMutableArray arrayWithArray:objects];
        for (FindModel *find in _recentlyArray) {
            find.startTime = [self getStartTimeWith:find.createdAt];
            [self getNumbersOfReplyWithOnlyID:find.objectId didFinished:^(NSInteger number) {
                find.replys = number;
            }];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            success(_recentlyArray);
        });
    }];
}
//最热 数据请求
-(void)requestHotArraydidFinish:(TEMP)success{

        if (_hotArray.count != 0) {
            [self.hotArray removeAllObjects];
        }
        AVQuery *query = [AVQuery queryWithClassName:@"FindModel"];
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    //设置缓存有效期
    query.maxCacheAge = 24*3600;
        [query includeKey:@"owner"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            self.recentlyArray = [NSMutableArray arrayWithArray:objects];
            for (FindModel *find in _recentlyArray) {
                find.startTime = [self getStartTimeWith:find.createdAt];
                [self getNumbersOfReplyWithOnlyID:find.objectId didFinished:^(NSInteger number) {
                    find.replys = number;
            find.startTime = [self getStartTimeWith:find.createdAt];
                    success(find);
                    [self.hotTVReloadDelegate  hotTVreload];
                }];
            }
      }];
}
//社区-->话题 请求数据
-(void)requestHotchatArrayWithArrayType:(NSString *)arrayType didFinish:(SUCCESS)success{

    if (_hotChatArray.count != 0 ) {
        [_hotChatArray removeAllObjects];
    }
    AVQuery *query = [FindModel query];
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    //设置缓存有效期
    query.maxCacheAge = 24*3600;
    [query whereKey:@"mHTopicType" equalTo:arrayType];
    [query includeKey:@"owner"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.hotChatArray = [NSMutableArray arrayWithArray:objects];
        
        for (FindModel *find in _hotChatArray) {
            find.startTime = [self getStartTimeWith:find.createdAt];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            success(_hotChatArray);
        });
    }];
}
//回复 数据请求
-(void)requestReplyArrayWithOnlyID:(NSString *)onlyID didFinish:(SUCCESS)success{
    
    AVQuery *query = [ReplyModel query];
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    //设置缓存有效期
    query.maxCacheAge = 24*3600;
    [query includeKey:@"replyer"];
    AVObject *find = [AVObject objectWithoutDataWithObjectId:onlyID];
    [query whereKey:@"targetFindModel" equalTo:find];
    [query includeKey:@"replyer"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        self.replyArray = [NSMutableArray arrayWithArray:objects];
        for (ReplyModel *reply in objects) {
        reply.startTime = [self getStartTimeWith:reply.createdAt];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            success(_replyArray);
        });
    }];
}

//我关注的 所有用户 的话题
-(void)requestAllMyAttentionTopicdidFinished:(SUCCESS)success{
    
    if (_allMyAttentionTopics.count != 0) {
        [self.allMyAttentionTopics removeAllObjects];
    }
    
    AVQuery *query = [FindModel query];
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    //设置缓存有效期
    query.maxCacheAge = 24*3600;
    [query includeKey:@"owner"];
    NSArray *array = [AVUser currentUser][@"myAttention"];
    if (array) {
        [query whereKey:@"owner" containedIn:array];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            
            self.allMyAttentionTopics = [NSMutableArray arrayWithArray:objects];
            for (FindModel *find in objects) {
                find.startTime = [self getStartTimeWith:find.createdAt];
            }
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                success(_allMyAttentionTopics);
            });
        }];
    }
    
    
}

-(void)getNumbersOfFindModelInTopicWithArrayType:(NSString *)arrayType didFinished:(NUMBER)numbers{
    
    if (_hotChatArray.count != 0 ) {
        [_hotChatArray removeAllObjects];
    }
    AVQuery *query = [FindModel query];
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    //设置缓存有效期
    query.maxCacheAge = 24*3600;
    [query whereKey:@"mHTopicType" equalTo:arrayType];
    [query countObjectsInBackgroundWithBlock:^(NSInteger number, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            numbers(number);
        });
    }];
    
}

//获取 指定动态消息 的 回复数量//===================
-(void)getNumbersOfReplyWithOnlyID:(NSString *)onlyID didFinished:(NUMBER)numbers{
    FindModel *object  = [FindModel objectWithoutDataWithObjectId:onlyID];
    AVQuery *query = [ReplyModel query];
    [query whereKey:@"targetFindModel" equalTo:object];
    [query countObjectsInBackgroundWithBlock:^(NSInteger number, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            numbers(number);
        });
    }];
}
//歌曲 数据请求
-(void)requestAllSongsWithAllLike:(NSString *)allLike didFinished:(SUCCESS)success{
    [MHShareDataBlock GETAsynchronousBlockWithURL:allLike PassBlock:^(NSData *data) {
        
        if (_allSongsArray.count != 0) {
            [self.allSongsArray removeAllObjects];
        }
        
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
        for (NSDictionary *dic in [Dic[@"data"] valueForKey:@"songs"]) {
            SongModel *song = [SongModel new];
            [song setValuesForKeysWithDictionary:dic];
            if (song.urlList.count > 0) {
                [self.allSongsArray addObject:song];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            success(_allSongsArray);
        });
        
    }];
}
//歌曲 猜你喜欢
-(void)requestAllSongsWithGuess:(NSString *)guessS didFinished:(SUCCESS)success{
    
    if (_allSongsArray.count != 0) {
        [self.allSongsArray removeAllObjects];
    }
    
    [MHShareDataBlock GETAsynchronousBlockWithURL:guessS PassBlock:^(NSData *data) {
        
        NSDictionary *Dic = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingAllowFragments) error:nil];
        for (NSDictionary *dic in Dic[@"data"]) {
            SongModel *song = [SongModel new];
            [song setValuesForKeysWithDictionary:dic];
            if (song.urlList.count > 0) {
                [self.allSongsArray addObject:song];
            }
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            success(_allSongsArray);
        });
    }];
}




//查看个人信息 他发布的所有主题（数据请求）

-(void)requestAllHerTopicWith:(NSString *)personalID didFinished:(SUCCESS)success{
    
    if (_allHerTopics.count != 0) {
        [self.allHerTopics removeAllObjects];
    }
    
    AVUser *user = [AVUser objectWithoutDataWithObjectId:personalID];
    AVQuery *query = [FindModel query];
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    //设置缓存有效期
    query.maxCacheAge = 24*3600;
    [query includeKey:@"owner"];
    [query whereKey:@"owner" equalTo:user];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

        self.allHerTopics = [NSMutableArray arrayWithArray:objects];
        for (FindModel *find in _allHerTopics) {
            find.startTime = [self getStartTimeWith:find.createdAt];
            [self getNumbersOfReplyWithOnlyID:find.objectId didFinished:^(NSInteger number) {
                find.replys = number;
            }];
        
        }
        dispatch_async(dispatch_get_main_queue(), ^{
                   success(_allHerTopics);
        });
    
    }];
    
}

//查看个人信息 他的所有回复（数据请求）
-(void)requestAllHerReplysWith:(NSString *)personalID didFinished:(SUCCESS)success{
    
    if (_allHerReplys.count != 0) {
        [self.allHerReplys removeAllObjects];
    }
    
    AVUser *user = [AVUser objectWithoutDataWithObjectId:personalID];
    
    AVQuery *query = [ReplyModel query];
    query.cachePolicy = kAVCachePolicyNetworkElseCache;
    //设置缓存有效期
    query.maxCacheAge = 24*3600;
    [query includeKey:@"replyer"];
    [query includeKey:@"targetFindModel"];
    [query whereKey:@"replyer" equalTo:user];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
       
        self.allHerReplys = [NSMutableArray arrayWithArray:objects];
        for (ReplyModel *reply in _allHerReplys) {
        reply.startTime = [self getStartTimeWith:reply.createdAt];
            
            reply.replyTopic = [NSString stringWithFormat:@"在主题《%@》中的回复我",reply[@"targetFindModel"][@"topicMessage"]];
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            success(_allHerReplys);
        });
        
    }];

}
//我的收藏 话题
-(void)requestTopicOfMyCollectdidFinished:(SUCCESS)myCollect{
    
    if ([AVUser currentUser][@"myCollect"]) {
        NSArray *array = [AVUser currentUser][@"myCollect"];
        self.myCollectArray = [NSMutableArray arrayWithArray:array];
            NSLog(@"%ld",self.myCollectArray.count);
        }
    dispatch_async(dispatch_get_main_queue(), ^{
        myCollect(_myCollectArray);
    });
    
}
//=========================特殊方法===============================
//转换发布时间的显示格式 创建时间NSDate->发布时间NSString
-(NSString *)getStartTimeWith:(NSDate *)createdAt{
    NSDateFormatter *format = [NSDateFormatter new];
    [format setDateFormat:@"dd"];
    
    NSDate *select = createdAt;
    NSString *string1 = [format stringFromDate:select];
    NSInteger day = [string1 intValue];
    
    NSDate *select0 = [NSDate date];
    NSString *string0 = [format stringFromDate:select0];
    NSInteger today = [string0 intValue];
    
    [format setDateFormat:@"HH"];
    NSString *string2 = [format stringFromDate:select];
    NSInteger hour = [string2 intValue];
    [format setDateFormat:@"mm"];
    NSString *string3 = [format stringFromDate:select];
    NSInteger minutes = [string3 intValue];
    
    if (today-day == 0) {
        return  [NSString stringWithFormat:@"今天%02ld:%02ld",hour,minutes];
    }else if (today-day == 1||day - today == 30||day - today == 29) {
        return  [NSString stringWithFormat:@"昨天%02ld:%02ld",hour,minutes];
    }else if (today-day == 2||day - today == 28||day - today == 29) {
        return  [NSString stringWithFormat:@"前天%02ld:%02ld",hour,minutes];
    }else {
        return  [NSString stringWithFormat:@"3天前%02ld:%02ld",hour,minutes];
    }
}
//========================一般不改================================
//懒加载
-(NSMutableArray *)hotArray{
    if (!_hotArray) {
        _hotArray = [NSMutableArray array];
    }
    return _hotArray;
}
-(NSMutableArray *)recentlyArray{
    if (!_recentlyArray) {
        _recentlyArray = [NSMutableArray array];
    }
    return _recentlyArray;
}
-(NSMutableArray *)hotChatArray{
    if (!_hotChatArray) {
        _hotChatArray = [NSMutableArray array];
    }
    return _hotChatArray;
}
-(NSMutableArray *)replyArray{
    if (!_replyArray) {
        _replyArray = [NSMutableArray array];
    }
    return _replyArray;
}
-(NSMutableArray *)myCollectArray{
    if (!_myCollectArray) {
        _myCollectArray = [NSMutableArray array];
    }
    return _myCollectArray;
}
-(NSMutableArray *)allHerTopics{
    if (!_allHerTopics) {
        _allHerTopics = [NSMutableArray array];
    }
    return _allHerTopics;
}
-(NSMutableArray *)allHerReplys{
    if (!_allHerReplys) {
        _allHerReplys = [NSMutableArray array];
    }
    return _allHerReplys;
}
-(NSMutableArray *)onlineUsers{
    if (!_onlineUsers) {
        _onlineUsers = [NSMutableArray array];
    }
    return _onlineUsers;
}
-(NSMutableArray *)allSongsArray{
    if (!_allSongsArray) {
        _allSongsArray = [NSMutableArray array];
    }
    return _allSongsArray;
}
-(NSMutableArray *)topicNumbers{
    if (!_topicNumbers) {
        _topicNumbers = [NSMutableArray array];
    }
    return _topicNumbers;
}
@end
